package com.markyao.controller;

import com.markyao.utils.QiniuyunUtils;
import com.markyao.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("upload")
public class UploadController {
    @Autowired
    QiniuyunUtils qiniuyunUtils;

    @PostMapping
    public Result upload(@RequestPart("image")MultipartFile file, HttpServletRequest request){
        //原始文件名称
        String originalFilename = file.getOriginalFilename();
        //取后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //随机生成一个文件名
        String prefixx = UUID.randomUUID().toString();
        //拼接成唯一的文件名
        String fileName=prefixx+suffix;
        //上传到哪?  七牛云 云服务器 按量付费 速度快 把图片发放到离用户最近的服务器上面
        //降低自身服务器的带宽消耗

        boolean upload = qiniuyunUtils.upload(file, fileName);
        if(upload){
            return Result.success(QiniuyunUtils.url+fileName);
        }
        System.out.println("上传失败");
        return Result.failed(20001,"上传失败");
    }
}
